<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ include file="/jsp/common/common.jsp"%>  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">
        <link rel="stylesheet" type="text/css" href="<c:url value="/static/jquery-easyui/themes/default/easyui.css"/>">
        <link rel="stylesheet" type="text/css" href="<c:url value="/static/jquery-easyui/themes/icon.css"/>">
        <script type="text/javascript" src="<c:url value="/static/jquery-easyui/jquery-1.6.min.js"/>"></script>
        <script type="text/javascript" src="<c:url value="/static/jquery-easyui/jquery.easyui.min.js"/>"></script>
        <script type="text/javascript" src="<c:url value="/static/jquery-easyui/plugins/jquery.panel.js"/>"></script>
        <script type="text/javascript" src="<c:url value="/static/jquery-easyui/plugins/jquery.datagrid.js"/>"></script>
        <script type="text/javascript" src="<c:url value="/static/jquery-easyui/plugins/jquery.messager.js"/>"></script>
        <script type="text/javascript" src="<c:url value="/static/jquery-easyui/ext-for-framework.js.jsp"/>"></script>
        <script type="text/javascript" src="<c:url value="/static/jquery-easyui/locale/easyui-lang-zh_CN.js"/>"></script>   
        <script type="text/javascript" src="<c:url value="/static/js/common.js"/>"></script>
 
        <script>
			function initList(listDisplayEId) {
				$('#' + listDisplayEId).datagrid(
						{
							url:"<c:url value="/materSup/findSelectMaterForBuySupplier.do"/>"+"?custId=" +"${selectMaterVo.ordCustId }",
							nowrap : false,
							striped : true,
							collapsible : true,
							remoteSort : true,
							notSelectByRow : false,
							onLoadError:function(){
								$.messager.alert('错误','获取数据失败，请与管理员联系！','error');
							},
							onLoadSuccess:function(){ 
                                $(".datagrid-row").mouseover(function(e){  
                                    if(checkHover(e,this)){
                                        var foodId = $(this).find('td').eq(1).text();
                                        var index = $('#listDisplay').datagrid('getRowIndex', foodId);
                                        $('#listDisplay').datagrid('beginEdit',index);
                                    }
                                }); 
                                
                            } 
						
						});
				
			};
			
			function initList2(listDisplayEId) {
                $('#' + listDisplayEId).datagrid(
                        {
                            nowrap : false,
                            striped : true,
                            collapsible : true,
                            remoteSort : true,
                            notSelectByRow : false,
                            toolbar : [
                                       {
                                           id : listDisplayEId + '_btn_edit',
                                           text : '提交',
                                           iconCls : 'icon-edit',
                                           handler : function() {  
                                               
                                               var rows = $('#listDisplay2').datagrid('getRows');  
                                               for(var i=0; i<rows.length; i++){
                                                   var rowIndex=$('#listDisplay2').datagrid('getRowIndex',rows[i]['sid']);
                                                   $('#listDisplay2').datagrid('endEdit', rowIndex);
                                               }
                                               var row = $('#listDisplay2').datagrid('getRows');   
                                               if(row.length == 0){
                                                   $.messager.alert('提示','购物车中没有商品！','info');
                                                   return;
                                               }else{
                                                   var userList = new Array(); 
                                                   var jsonFater;
                                                   for (var i = 0 ; i < row.length;i++){
                                                	   if (!isNumber(row[i]['materValueCost'])) {
                                                           $.messager.alert("提示",
                                                                   "'" + row[i]['materValueCost'] + "'金额请填写数字！", 'info');
                                                           return;
                                                       }
                                                       var jsonSun = "{materId:'"+row[i]['materId']+"',date:'"+document.getElementById("orderDate").value+"',leaveMessage:'"+row[i]['leaveMessage']+"',materValue:'"+row[i]['materValue']+"',materValueCost:'"+row[i]['materValueCost']+"',supId:'${supId }',materNum:'"+row[i]['materNum']+"',materLevel:'"+row[i]['materLevel']+"'}";
                                                       userList.push(jsonSun);
                                                   }
                                                   jsonFater = JSON.stringify(userList);
                                                   var str = "json="+jsonFater;    
                                                   document.getElementsByName("materdategridList")[0].value = jsonFater;
                                                   $.messager.confirm('提示', '是否提交记录？', function(r){
                                                       //方法函数 进入后台
                                                       if(r){
                                                           addMater();
                                                       }
                                                   });
                                               }
                                           }
                                       }
                                      ],
                            onLoadSuccess:function(){ 
                                $(".datagrid-row").mouseover(function(e){  
                                    if(checkHover(e,this)){
                                        var foodId = $(this).find('td').eq(0).text();
                                        var index = $('#listDisplay2').datagrid('getRowIndex', foodId);
                                        $('#listDisplay2').datagrid('beginEdit',index);
                                    }
                                }); 
                                
                                $(".datagrid-row").mouseout(function(e){  
                                    if(checkHover(e,this)){
                                        var foodId = $(this).find('td').eq(0).text();
                                        var index = $('#listDisplay2').datagrid('getRowIndex', foodId);
                                        $('#listDisplay2').datagrid('endEdit',index);
                                    }
                                });
                            } 
                        });
            };
			$(document).ready(function() {
                initList2('listDisplay2');
                initList('listDisplay');
			});
			
 			function addMater(){
 	 			$('#AddMaterForm').form('submit',
 				{
 					url:'<c:url value='/orderSup/commitMaterOrderForUpdate.do'/>', //查询提交路径
 					onSubmit:function()//提交按钮相应函数
 					{
 						return $('#AddMaterForm').form('validate');
 					},
 					success:function(data){
 						data = eval( "("+data+")" );
 		       			if(data.success){
 		       				$.messager.alert("提示", "提交成功！", 'info');
 		       			   /*  $('#listDisplay').datagrid('reload');
                            $('#listDisplay').datagrid('clearSelections');
                            $('#listDisplay2').datagrid('reload'); */
                            history.go(-2);
 	       				}else{
 	                        var message = "";
 	                        if(data.msg == "ms001"){
 	                            message = "订单中已有购物车中的材料，请直接改实际送货数量。";
 	                        }else if(data.msg == "msg001"){
                                message = "选择材料的时间已过，请联系采购部。";
                            }
 	                        $.messager.alert("提示", message, 'warning');
 	                    }
 					},
 					error:function(){
 						$.messager.alert("错误", "系统错误，请联系管理员！", 'error');
 						return;
 					}
 				});
 	 			
 			}
 			//下拉框
			$(function() {        
		        $('#materType').combobox({   
                    url:"<c:url value='/mater/pulldownMaterType.do?space=1'/>",   
                    editable:true, //不可编辑状态  
                    cache: false,  
                    panelHeight: '150',  
                    valueField:'materType',     
                    textField:'materTypename',                      
                    }); 
		    });
 			
			function searchInfo(){
				var midvale;
				if($('#mid').val()==''){
					midvale = 0;
				}else {
					midvale =$('#mid').val();
				}
				
				
				if($('#materType').combobox('getValue') ==''){
					$('#listDisplay').datagrid('load', {
						materType : 0,
						materName : $('#materName').val(),
						supName : $('#supName').val(),
						mid : midvale
					}); 
				}else{
					$('#listDisplay').datagrid('load', {
						materType : $('#materType').combobox('getValue'),
						materName : $('#materName').val(),
						supName : $('#supName').val(),
                        mid : midvale
					});  
				}
			}
			
			function  goDetailedContent(val,rowData,rowIndex){
		        return '<a href="#" onclick="constructionManager(\'' + rowIndex+ '\')">'+val+'</a>  '
		    }
		    
		    function constructionManager(rowIndex) {
                var rows = $('#listDisplay').datagrid('getRows');   
		    	var new_win = window.open("<c:url value='/jsp/openIndexSun.jsp?url=/mater/preLookMaterValue.do'/>"+"?materId="+rows[rowIndex]['materId']+"&materLevel="+rows[rowIndex]['materLevel'] +"&supId="+rows[rowIndex]['supId'] ,"sun","width=1200px,height=600px,status=no,scrollbars=yes");
                new_win.focus();
		    }
		    function formatOptionField(val,rowData,rowIndex){
                var a= rowData['sid']+'';
                return "<a href='###' onclick='editrow("+a+")'><img src='../images/cancel.png'/></a>";
            }
            function formatShoppingCart(val,rowData,rowIndex){
                return "<a href='###' onclick='shoppingCart("+rowIndex+")'><img src='../images/gouwuche.png'/></a>";
            }
            function editrow(sid){
                $.ajax({
                    async : false,
                    url : "<c:url value='/materSup/deleteShoppingCartOne.do'/>" +"?sid="+sid,
                    type : "post",
                    success : function(data) {
                        if(typeof(data)=='string'){
                            dataJson =JSON.parse(data);
                        }else{
                            dataJson = data;
                        }
                        if(dataJson.success){
                            $.messager.alert('提示','删除成功','info');
                            $('#listDisplay2').datagrid('load');
                        }else{
                            $.messager.alert('提示','删除失败，请刷新页面重新删除！','info');
                        }
                    }
                });
            }
            function shoppingCart(rowIndex){
                var rowData ;
                var a ;
                var dateone;
                $('#listDisplay').datagrid('endEdit', rowIndex);
                var rowDateAll = $('#listDisplay').datagrid('getRows');
                for(var i=0; i<rowDateAll.length; i++){
                    if(rowIndex ==$('#listDisplay').datagrid('getRowIndex',rowDateAll[i]['mid'])) {
                        $('#listDisplay').datagrid('endEdit', rowIndex);
                        rowData = rowDateAll[i];
                        if ( !isNumberAndNoZero(rowData['materNum'])  ){
                            $.messager.alert('提示',"材料"+rowData['materName']+"，重量请填写数字！",'info');
                            return false;
                        }
                        if(strlen(rowData['leaveMessage'])>50){
                            $.messager.alert('提示',"材料"+rowData['materName']+"，留言请小于50字！",'info');
                            return false;
                        }
                        var leaveMessage =rowData['leaveMessage'];
                        if(leaveMessage==undefined){
                            var leaveMessage = "";
                            return false;
                        }
                        dateone = '{"materId":"'+ rowData['materId']+'","materNum":"'+rowData['materNum'] +'","materLevel":"'+rowData['materLevel']+'","materValue":"' + rowData['materValue']+'","materProportion":"'+ rowData['materProportion'] +'","materValueUndressed":"'+ rowData['materValueUndressed']+'","supId":"'+ rowData['supId']+'","custId":"${sessionScope.user.userId }","leaveMessage":"'+leaveMessage+'"}';
                        break;
                    }
                }
                dataOneJson =JSON.parse(dateone);
                $.ajax({
                    async : false,
                    url : "<c:url value='/materSup/addShoppingCart.do'/>" ,
                    type : "post",
                    dataType: "json",
                    data: $.param(dataOneJson),
                    success : function(data) {
                        if(typeof(data)=='string'){
                            dataJson =JSON.parse(data);
                        }else{
                            dataJson = data;
                        }
                        if(dataJson.success){
                            $.messager.alert('提示','成功放入购物车。','info');
                            $('#listDisplay2').datagrid('load');
                        }else{
                            $.messager.alert('提示','购物车已有此种商品，请在购物车中修改数量！','info');
                        }
                    }
                });
            }
            
            document.onkeydown=keyDownSearch;  
            function keyDownSearch(e) {  
                // 兼容FF和IE和Opera    
                var theEvent = e || window.event;    
                var code = theEvent.keyCode || theEvent.which || theEvent.charCode;    
                if (code == 13) {    
                    searchInfo();//具体处理函数    
                    return false;    
                }    
                return true;    
            }  
		</script>
			</head>
			<body>
			<form id="excelForm" name="excelForm" method="post"  enctype="multipart/form-data"
                        action="userlist.txt"
                        onsubmit="return searchDGData(this.id,'listDisplay');">
            </form>
			<form id="AddMaterForm" name="AddMaterForm" method="post" enctype="multipart/form-data">
			<table width="98%">
			<tr><td>
			<div style="height: auto; width:100%;background: #fafafa; padding: 2px;" class="easyui-panel" title="&nbsp&nbsp&nbsp&nbsp&nbsp订单信息"  collapsible="true" minimizable="false" maximizable="false" closable="false">
			   <table cellpadding="5">
			      <tr>
                  	<td>材料使用日期</td>
                    <td>
 			            <input class="easyui-validatebox" value="${selectMaterVo.ordDate }" name="orderDate" id="orderDate" editable="false" readOnly="true"/> 
 			        </td>
                    <td>订单号</td>
                    <td>
                        <input class="easyui-validatebox" value="${selectMaterVo.ordId }" name="ordId" id="ordId" editable="false" readOnly="true"/> 
                    </td>
                    <td>客户</td>
                    <td>
                        <input class="easyui-validatebox" value="${selectMaterVo.ordCustName }" name="ordCustName" id="ordCustName" editable="false" readOnly="true"/> 
                    </td>
                    <td>
                        <input class="easyui-validatebox" value="${selectMaterVo.ordCustId }" name="ordCustId" id="ordCustId" editable="false" readOnly="true" hidden="true"/> 
                    </td>
                  </tr>
                  <tr>
                    <td>
				        <input class="easyui-validatebox" type="hidden" name="materdategridList"  />
 			        </td>
                  </tr>
               </table>
             </div>
           </td></tr>
           <tr><td>
			<div style="height: auto; width:100%;background: #fafafa; padding: 5px;" class="easyui-panel" title="查询" iconCls="icon-search" collapsible="true" minimizable="false" maximizable="false" closable="false">
					<form id="searchForm" name="searchForm" method="post"
						action="userlist.txt"
						onsubmit="return searchDGData(this.id,'listDisplay');">
						<div>
		            	<table cellpadding="5">
		            	        <tr>
		            	            <td colspan="3"><span style="color:red;">(注意!材料名支持拼音和首字母检索)</span></td>
		            	        </tr>
								<tr>
									<td>材料名：</td>
									<td><input class="easyui-validatebox" id="materName" editable="true" name="materName"></input></td>
									<td>ID：</td>
                                    <td><input class="easyui-numberbox" id="mid" editable="true" name="mid" validType="length[1,30]"></input></td>
									<td>类别：</td>
									<td><input class="easyui-combobox" id="materType" editable="false" name="materType"></input></td>
									<!-- <td>供货商名：</td> -->
									<td><input class="easyui-validatebox" id="supName" editable="true" name="supName"  hidden= "true"></input></td>
									
		                    		<td><input type="button" onclick="searchInfo()" value="查询"></td>
		                    	</tr>
		                </table>					 
						</div>
					</form>
				</div>
			</td></tr>
           </table>
		<table width="98%">
		<tr style="height: 12px;"></tr>
		<tr>
		<td>
				<table id="listDisplay" title="选取材料列表" 
			iconCls="icon-list" singleSelect="false" idField="mid"
			loadMsg="请稍候......"
			pagination="true" pageSize="10"
			pageList="[10,20,30,40,50,100]" sortName="mid"
			rownumbers="true" sortOrder="asc">
			<thead>
				<tr>
				    <th field="materRole" width="25" align="center"  checkbox="true" hidden='true'>
					</th> 
					<th field="mid" width="80" sortable="true" hidden="true">ID
					</th>
				    <th field="materId" width="40" sortable="true" hidden="true">材料ID
					</th>	
					<th field="button" width="120" align="center" formatter="formatShoppingCart">购物车</th>
					<th field="materNum" width="70" sortable="true" editor="text" align="center"  >数量
                    </th>   
                    <th field="unit" width="60"  sortable="true" >单位
                    </th>
 					<th field="materName" width="140"  sortable="true" >材料名
					</th>		
					<th field="materType" width="60" formatter="formatFoodType1" sortable="true" >种类
					</th>	
                    <th field="brands" width="60" sortable="true" >品牌
                    </th>
                    <th field="specifications" width="60" sortable="true" >规格
                    </th>
					<th field="materLevel" width="50" formatter="formatFoodType" sortable="true" hidden="true" >品级
					</th>	
					<th field="supId" width="80" sortable="true" hidden="true" >供货商ID
					</th>
					<th field="supName" width="80" sortable="true" hidden="true">供货商名
					</th>
					<th field="materValue" width="70"  sortable="true" align="right" hidden="true">净料价格
					</th>	
					<th field="materValueCost" width="60"  sortable="true" align="right" hidden='true'>进货价格
					</th>	
					<th field="materProportion" width="100"  sortable="true" align="right" hidden="true">毛料率（%）
					</th>
					<th field="leaveMessage" width="100"  editor="text"  sortable="true" align="right" >留言
                    </th>
 				</tr>
			</thead>
			</table>
			</td>
			</tr>
			<tr style="height: 12px;"></tr>
        <tr>
        <td>
                 <table id="listDisplay2" title="我的购物车" width="100%"
            url="<c:url value="/materSup/findShoppingCartMater.do"/>"
            iconCls="icon-list" singleSelect="false" idField="sid"
            loadMsg="请稍候......"
            pagination="false" sortName="sid"
            rownumbers="true" sortOrder="asc">
            <thead>
                <tr>
                    <th field="sid" width="80" sortable="true" hidden="true">
                        ID
                    </th>
                    <th field="materId" width="50" sortable="true" hidden="true">材料ID
                    </th>   
                    <th field="materNum" width="50" sortable="true" editor="text" align="center"  >数量
                    </th>
                    <th field="unit" width="60"  sortable="true" >单位
                    </th>
                    <th field="materName" width="80"  sortable="true" >材料名
                    </th>       
                    <th field="materType" width="60" formatter="formatFoodType1" sortable="true" >种类
                    </th>   
                    <th field="brands" width="50" sortable="true" >品牌
                    </th>
                    <th field="specifications" width="60" sortable="true" >规格
                    </th>
                    <th field="materLevel" width="50" formatter="formatFoodType" sortable="true" hidden="true">品级
                    </th>   
                    <th field="supId" width="80" sortable="true" hidden="true" >供货商ID
                    </th>
                    <th field="supName" width="80" sortable="true" hidden="true" >供货商名
                    </th>
                    <th field="materValue" width="70"  sortable="true" align="right" hidden="true">净料价格
                    </th>   
                    <th field="materValueCost" width="60" editor="text" sortable="true" align="right">进货价格
                    </th>   
                    <th field="materProportion" width="50"  sortable="true" align="right" hidden="true">毛料率（%）
                    </th>
                    <th field="leaveMessage" width="100"  editor="text"  sortable="true" align="right" >留言
                    </th>
                    <th field="button" width="40" align="center" formatter="formatOptionField">删除</th>
                </tr>
            </thead>
            </table>
            </td>
            </tr>
		</table>
		</form>
	</body>
</html>
